package com.luguotao.lease.web.admin.service.impl;

import com.luguotao.lease.common.minio.MinioProperties;
import com.luguotao.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
//写全部的业务逻辑
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties properties;
    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) {

        try {
            //桶的名字
            String bucketName = properties.getBucketName();
            //判断桶是否存在
            boolean result = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!result) {
                //创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                String policy = """
                          {
                                       "Statement" : [ {
                                         "Action" : "s3:GetObject",
                                         "Effect" : "Allow",
                                         "Principal" : "*",
                                         "Resource" : "arn:aws:s3:::%s/*"
                                       } ],
                                       "Version" : "2012-10-17"
                                     }
                        """.formatted(bucketName);
                //设置访问策略
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
            } else {
                //桶已存在
            }

            //上传文件
            // 1.设置文件别名(在桶容器中保证文件的名字是具备唯一性的)
            String fileName= new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+ UUID.randomUUID()+"-"+file.getOriginalFilename();
            //2. 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .contentType(file.getContentType())
                    .build());

            //url: minio服务器中的文件的路径   endpoint+bucketName+fileName  --> http://192.168.64.136/lease/xxxxxx.jpg

            return  String.join("/",properties.getEndpoint(),properties.getBucketName(),fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }
}
